package com.cpoopc.fuckapp.utils;/**
 * Created by cpoopc on 2015/8/21.
 */

import android.app.ActivityManager;
import android.content.Context;
import android.os.Handler;
import android.text.TextUtils;
import android.widget.Toast;

import java.util.Iterator;
import java.util.List;

/**
 * User: cpoopc
 * Date: 2015-08-21
 * Time: 13:21
 * Ver.: 0.1
 */
public class GlobalToast {
    private static final int DEFAULT_DURATION = 2000;
    private static Toast mToast;
    private static Handler mHandler = new Handler();
    private static Runnable r = new Runnable() {
        public void run() {
            if (null != GlobalToast.mToast) {
                GlobalToast.mToast.cancel();
            }

        }
    };

    private GlobalToast() {
    }

    public static void showToast(Context ctx, String text) {
        if (ctx != null) {
            ctx = ctx.getApplicationContext();
        }

        mHandler.removeCallbacks(r);
        if (!isBackgroundRunning(ctx) && !TextUtils.isEmpty(text)) {
            if (mToast != null) {
                mToast.setText(text);
            } else {
                mToast = Toast.makeText(ctx, text, Toast.LENGTH_SHORT);
            }

            mHandler.postDelayed(r, DEFAULT_DURATION);
            mToast.show();
        }
    }

    public static void showToast(Context ctx, int resId) {
        if (ctx != null) {
            ctx = ctx.getApplicationContext();
        }

        if (resId > 0) {
            showToast(ctx, ctx.getResources().getString(resId));
        }
    }

    public static boolean isBackgroundRunning(Context context) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        if (activityManager == null) {
            return false;
        } else {
            List processList = activityManager.getRunningAppProcesses();
            Iterator i$ = processList.iterator();

            ActivityManager.RunningAppProcessInfo process;
            do {
                if (!i$.hasNext()) {
                    return false;
                }

                process = (ActivityManager.RunningAppProcessInfo) i$.next();
            } while (!process.processName.startsWith(context.getPackageName()));

            boolean isBackground = process.importance != 100 && process.importance != 200;
            if (isBackground) {
                return true;
            } else {
                return false;
            }
        }
    }

}
